namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;    

    /// <summary>
    /// 1. Starts at Sales homepage
    /// 2. Click on Leads
    /// 3. Select Open Leads view
	/// 4. Add random string of two characters in look for textbox and click find
    /// 5. Double click a lead
    /// 6. Select Activities
    /// 7. Click New Activity
    /// 8. Select Phone Call and click OK
    /// 9. Add random string to Subject and Description
    /// 10. Click Save & Close
    /// 11. Click Save & Close
    /// </summary>

    public class AddActivityToLead : CrmWebTest
    {
        public void AddActivityToLead_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }            

			EntityRequest LeadEr = new EntityRequest();
			LeadEr.Type = EntityNames.Leads;
			LeadEr.ParentID = Guid.NewGuid();
			LeadEr.ReturnAs = EntityNames.Leads;

			Props.Add(EntityNames.Accounts, new EntityRequest[] { LeadEr });

			er.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			lead = (CRMEntity)Entities[EntityNames.Leads];
            
            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);            
        }

        public void AddActivityToLead_PostWebTest(object sender, PostWebTestEventArgs e)
        {
			EntityManager.Instance.FreeEntity(user);
			EntityManager.Instance.FreeEntity(lead);
        }

        public AddActivityToLead()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            string random = Utils.GetRandomString(2, 2);
            gridXml = GridXmlHelper.LeadPageView(-1, openLeadsView, null);
            gridXml2 = GridXmlHelper.LeadSearchView(-1, searchLeadsView, random, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(AddActivityToLead_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(AddActivityToLead_PostWebTest);
        }

        static AddActivityToLead()
        {
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            gridRefreshXml = GridXmlHelper.ActivityGridForEntityViewRefresh(-1, activityView, null, lead[EntityIDNames.Lead], "4");
            AppGridWebService.AppGridWebService ag;
            WebTestRequest wtr;

			this.BeginTransaction("NavLeadHomepage");

            // Get the home page
            _root_homepage_aspx hp = new _root_homepage_aspx(user);
            hp.etc = 4;
            yield return (hp);

			this.EndTransaction("NavLeadHomepage");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavOpenLeads");

                // Open All Leads view
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;

                try { ag.Reset(gridXml, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    WRPCInfo rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    WebTestRequestHeader headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavOpenLeads");
            }

            this.BeginTransaction("SearchLeads");

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;
            try { ag.Reset(gridXml2, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("SearchLeads");

            this.BeginTransaction("OpenLead");

            // simulate double clicking of lead
            sfa_leads_edit_aspx dp = new sfa_leads_edit_aspx(user);
            dp.id = lead[EntityIDNames.Lead];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx fs = new _forms_FormScript_js_aspx(user);
            fs.etc = 4;
            fs.FormType = "main";
            fs.FormName = "crmForm";
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "referer";
            headerItem.Value = referer;
            fs.Headers.Add(headerItem);
            yield return (fs);

            this.EndTransaction("OpenLead");

            this.BeginTransaction("AddActivityToLead");

            sfa_leads_areas_aspx la = new sfa_leads_areas_aspx(user);
            la.oId = new Guid(lead[EntityIDNames.Lead]);
            la.oType = 4;
            la.security = 852023;
            la.tabSet = "areaActivities";
            yield return (la);

            activities_dlg_create_aspx createPage = new activities_dlg_create_aspx(user);
            yield return (createPage);

            activities_phone_edit_aspx phoneedit = new activities_phone_edit_aspx(user);
            phoneedit.pId = new Guid(lead[EntityIDNames.Lead]);
            phoneedit.pType = 4;
            phoneedit.pName = lead["firstname"] + "%20" + lead["lastname"];
            phoneedit.partyid = new Guid(lead[EntityIDNames.Lead]);
            phoneedit.partytype = 4;
            phoneedit.partyname = lead["firstname"] + "%20" + lead["lastname"];
            yield return (phoneedit);

            referer = phoneedit.lastResponse.ResponseUri.AbsoluteUri;

            fs = new _forms_FormScript_js_aspx(user);
            fs.etc = 4210;
            fs.FormType = "main";
            fs.FormName = "crmForm";
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "referer";
            headerItem.Value = referer;
            fs.Headers.Add(headerItem);
            yield return (fs);

            phoneedit = new activities_phone_edit_aspx(user);
            phoneedit.pId = new Guid(lead[EntityIDNames.Lead]);
            phoneedit.pType = 4;
            phoneedit.pName = lead["firstname"] + "%20" + lead["lastname"];
            phoneedit.partyid = new Guid(lead[EntityIDNames.Lead]);
            phoneedit.partytype = 4;
            phoneedit.partyname = lead["firstname"] + "%20" + lead["lastname"];

            phoneedit.crmFormSubmitXml = EntityXmlHelper.GetCreatePhonecallXml(new Guid(user["systemuserid"]),8,new Guid(lead[EntityIDNames.Lead]),4,new Guid(lead[EntityIDNames.Lead]), 4); // pc.Serialize();

            rpcInfo = Utils.GenerateWRPCToken(activities_phone_edit_aspx.url, user, tokenKey);
            phoneedit.CRMWRPCToken = rpcInfo.token;
            phoneedit.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            phoneedit.crmFormSubmitMode = 2;
            phoneedit.crmFormUserModified = true;
            phoneedit.crmFormSubmitObjectType = 4210;
            phoneedit.crmFormSubmitSecurity = 852023;
            phoneedit.crmFormSubmitOnline = 1;
            yield return (phoneedit);

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;
            try { ag.Refresh(gridRefreshXml); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

                                                
            this.EndTransaction("AddActivityToLead");
        }

        private const string newIdMarker = @"separator + ""id=";
        private string gridXml;
        private string gridXml2;
        private string gridRefreshXml;
        private static string gridId = "crmGrid";
        private static string openLeadsView = "00000000-0000-0000-00AA-000010001006";
        private static string searchLeadsView = "F1A7C4D9-F439-46DA-8B69-ECC133214695";
        private static string activityView = "00000000-0000-0000-00AA-000010001903";

        private CRMEntity user;
        private CRMEntity lead;
        private string crmServer;
        private string tokenKey;
        private string referer;

        private Guid orgId;
        private WebTestRequestHeader headerItem;
        private WRPCInfo rpcInfo;
    }
}